package com.lagou.edu.code.controller;

import com.lagou.edu.code.client.EmailClient;
import com.lagou.edu.code.entity.AuthCodeDO;
import com.lagou.edu.code.mapper.AutoCodeMapper;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author liangzj
 * @date 2021/6/24 23:44
 */
@CrossOrigin(originPatterns = "*")
@RefreshScope
@RestController
@RequestMapping("/code")
public class CodeController {

    @Value("${code.valid.timeout.second}")
    private Integer codeTimeout;

    @Autowired
    private EmailClient emailClient;
    @Autowired
    private AutoCodeMapper autoCodeMapper;

    /**
     * ⽣成验证码并发送到对应邮箱，成功true，失败false
     *
     * @param email
     * @return
     */
    @GetMapping("/create/{email}")
    public boolean create(@PathVariable String email) {
        // 生成6位验证码
        int code = new Random().nextInt(900000) + 100000;
        // 发送邮件
        boolean sendSuccess = emailClient.email(email, String.valueOf(code));
        // 插入数据表
        Date now = new Date();
        AuthCodeDO authCodeDO = new AuthCodeDO();
        authCodeDO.setEmail(email);
        authCodeDO.setCode(String.valueOf(code));
        authCodeDO.setCreatetime(now);
        authCodeDO.setExpiretime(DateUtils.addSeconds(now, codeTimeout));
        Integer insertRow = autoCodeMapper.insert(authCodeDO);

        return sendSuccess && insertRow > 0;
    }

    /**
     * 校验验证码是否正确，0正确1错误2超时
     *
     * @param email
     * @param code
     * @return
     */
    @GetMapping("/validate/{email}/{code}")
    public int valid(@PathVariable String email, @PathVariable String code) {
        List<AuthCodeDO> authCodeDOS = autoCodeMapper.listByEmailAndCode(email, code);

        // 没有验证码返回错误
        if (CollectionUtils.isEmpty(authCodeDOS)) {
            return 1;
        }

        // 取最近的一个
        AuthCodeDO authCodeDO = authCodeDOS.stream()
                .sorted(Comparator.comparing(AuthCodeDO::getCreatetime).reversed())
                .findFirst()
                .get();

        // 判断是否超时
        if (new Date().after(authCodeDO.getExpiretime())) {
            return 2;
        }

        // 判断输入是否正确
        return authCodeDO.getCode().equals(code) ? 0 : 1;
    }

}
